package com.efounder.chat.utils;

import android.util.Log;

import com.pansoft.library.CloudDiskBasicOperation;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.efounder.form.util.CloudUtil.CLOUD_BASE_URL;
import static com.efounder.form.util.CloudUtil.CREATEUSER;
import static com.efounder.form.util.CloudUtil.DOWNURL;
import static com.efounder.form.util.CloudUtil.PARENTID;


/**
 * Created by yqs on 2016/8/8.
 */

public class PansoftCloudUtil {
    private static final String TAG = "PansoftCloudUtil";
    private static CloudDiskBasicOperation operation = new CloudDiskBasicOperation();


    /**
     * 将文件上传云盘
     *
     * @param path 文件路径
     */
    public static void getCloudRes(String path, final UpLoadListener upLoadListener) {
        String fileName = path.substring(path.lastIndexOf("/") + 1, path.length()).replace(".pic", "");

        operation.cloudDiskUploadWeChatFile(path, fileName, CREATEUSER, PARENTID, CLOUD_BASE_URL, null, new CloudDiskBasicOperation.ReturnBack() {
            @Override
            public void onReturnBack(String result) throws JSONException {
                String fileid = "";
                String resultString = null;
                try {
                    JSONObject resultObject = new JSONObject(result);
                    resultString = resultObject.getString("result");
                    if (resultObject.has("fileid")) {
                        fileid = resultObject.getString("fileid");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if ("success".equals(resultString)) {
                    /**图片、视频、语音等资源路径*/
                    String resUrl = String.format(CLOUD_BASE_URL + DOWNURL, fileid);

                    Log.i(TAG, resUrl);
                    if (upLoadListener != null) {
                        upLoadListener.getHttpUrl(true, resUrl);
                    }
                } else {
                    upLoadListener.getHttpUrl(false, null);
                }
            }
        });
    }


    /**
     * 云盘上传 支持进度回调
     *
     * @param path
     * @param upLoadListener
     * @param progressListener
     */
    public static void cloudUploadWithProgress(final String path, final UpLoadListener upLoadListener, final ProgressListener progressListener) {
        String fileName = path.substring(path.lastIndexOf("/") + 1, path.length()).replace(".pic", "");

        operation.cloudDiskUploadWeChatFile(path, fileName, CREATEUSER, PARENTID, CLOUD_BASE_URL, new CloudDiskBasicOperation.UploadProgress() {
            @Override
            public void onUploadProgress(long bytesRead, long contentLength, boolean done) {
                if (progressListener != null) {
                    progressListener.progress(path, (int) (bytesRead * 100.0 / contentLength));
                }
            }
        }, new CloudDiskBasicOperation.ReturnBack() {
            @Override
            public void onReturnBack(String result) throws JSONException {
                String fileid = "";
                String resultString = null;
                try {
                    JSONObject resultObject = new JSONObject(result);
                    resultString = resultObject.getString("result");
                    if (resultObject.has("fileid")) {
                        fileid = resultObject.getString("fileid");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if ("success".equals(resultString)) {
                    /**图片、视频、语音等资源路径*/
                    String resUrl = String.format(CLOUD_BASE_URL + DOWNURL, fileid);
                    Log.i(TAG, resUrl);
                    if (upLoadListener != null) {
                        upLoadListener.getHttpUrl(true, resUrl);
                    }
                } else {
                    upLoadListener.getHttpUrl(false, null);
                }
            }
        });
    }


    /**
     * 云盘多文件按顺序上传
     *
     * @param list                文件列表
     * @param multiUpLoadListener 回调
     */
    public static void syncMultiFileUpload(List<? extends CloudFile> list, final MultiUpLoadListener multiUpLoadListener) {
        if (list == null || (list != null && list.size() == 0)) {
            if (multiUpLoadListener != null) {
                multiUpLoadListener.uploadFail("list不能为空");
            }
            return;
        }
        int currentPosition = 0;
        List<String> urlList = new ArrayList<>();
        upLoadFile(currentPosition, list, multiUpLoadListener, urlList);

    }

    /**
     * 递归上传
     *
     * @param currentPosition     当前上传的position
     * @param list                文件列表
     * @param multiUpLoadListener 回调
     * @param urlList             上传完成后的url 数组
     */
    private static void upLoadFile(final int currentPosition, final List<? extends CloudFile> list,
                                   final MultiUpLoadListener multiUpLoadListener, final List<String> urlList) {

        final CloudFile cloudFile = list.get(currentPosition);
        cloudUploadWithProgress(cloudFile.getCloudFilePath(), new UpLoadListener() {
            @Override
            public void getHttpUrl(Boolean isSuccess, String url) {
                if (isSuccess) {
                    //上传成功
                    cloudFile.setCloudFileUrl(url);
                    urlList.add(url);
                    cloudFile.setCloudProgress(100);
                    cloudFile.setUploadSuccess(true);
                    if (currentPosition == list.size() - 1) {
                        if (multiUpLoadListener != null) {
                            multiUpLoadListener.upLoadFinish(urlList, list);
                        }
                        return;
                    }
                    upLoadFile(currentPosition + 1, list, multiUpLoadListener, urlList);
                } else {
                    //上传失败 继续上传下一个文件
                    cloudFile.setUploadSuccess(false);
                    cloudFile.setCloudProgress(-1);//-1表示上传失败
                    if (currentPosition == list.size() - 1) {
                        if (multiUpLoadListener != null) {
                            multiUpLoadListener.upLoadFinish(urlList, list);
                        }
                        return;
                    }
                    upLoadFile(currentPosition + 1, list, multiUpLoadListener, urlList);
                }
            }
        }, new ProgressListener() {
            @Override
            public void progress(String path, int percent) {
                if (multiUpLoadListener != null) {
                    multiUpLoadListener.uploadProgress(currentPosition, percent, cloudFile);
                }
            }
        });

    }

    /**
     * 多文件同步上传回调
     */
    public interface MultiUpLoadListener {
        /**
         * 上传进度
         *
         * @param position  文件position
         * @param progress  进度 0-100
         * @param cloudFile 文件对象
         */
        void uploadProgress(int position, int progress, CloudFile cloudFile);

        /**
         * 上传完成回调
         * @param urlList 文件云盘url
         * @param cloudFileList 源文件数组
         */
        void upLoadFinish(List<String> urlList, List<? extends CloudFile> cloudFileList);

        void uploadFail(Object message);
    }

    public static abstract class CloudFile {
        private String cloudFileUrl;//文件上传之后的url
        private String cloudFilePath;//本地文件路径
        private int cloudProgress = -1;//上传进度
        private boolean uploadSuccess;//是否上传成功

        public String getCloudFileUrl() {
            return cloudFileUrl;
        }

        public CloudFile setCloudFileUrl(String cloudFileUrl) {
            this.cloudFileUrl = cloudFileUrl;
            return this;
        }

        public String getCloudFilePath() {
            return cloudFilePath;
        }

        public CloudFile setCloudFilePath(String cloudFilePath) {
            this.cloudFilePath = cloudFilePath;
            return this;
        }

        public int getCloudProgress() {
            return cloudProgress;
        }

        public CloudFile setCloudProgress(int cloudProgress) {
            this.cloudProgress = cloudProgress;
            return this;
        }

        public boolean isUploadSuccess() {
            return uploadSuccess;
        }

        public CloudFile setUploadSuccess(boolean uploadSuccess) {
            this.uploadSuccess = uploadSuccess;
            return this;
        }
    }

    /**
     * 单文件上传回调
     */
    public interface UpLoadListener {
        void getHttpUrl(Boolean isSuccess, String url);
    }

    /**
     * 文件上传进度监听,
     * 这里将进度单独抽成一个接口方便用户配置,不过不监听上传进度可以直接将参数写为null;
     */
    public interface ProgressListener {
        /**
         * @param path    上传文件的路径;
         * @param percent 0-1 保留小数点两位
         */
        void progress(String path, int percent);
    }

    /**
     * 获取普联云盘上传的文件的文件id（仅限该云盘）
     *
     * @param fileUrl
     * @return
     */
    public static String getPansoftCloudFileId(String fileUrl) {
        String fileName = System.currentTimeMillis() + "";
        try {
            String fileName1 = fileUrl.substring(0, fileUrl.lastIndexOf("/"));
            fileName = fileName1.substring(fileName1.lastIndexOf("/") + 1, fileName1.length());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return fileName;
        }
    }
}

